<template>
  <div class="home" @touchmove="homePageTouch" @click="homePageTouch">
    <header>
      <!-- <div class="state"></div> -->
      <div class="nav">
        <div style="color:#fff;" @click="logout">{{name}}</div>
        <div>
          <button @click="allTagPopup" :style="{'backgroundColor': tagColor}">{{switchTagVal}}</button>
        </div>
        <router-link tag="div" to="/search">
          <img src="../assets/search.svg" alt />
        </router-link>
      </div>
    </header>
    <div class="choose-btn">
      <div>
        <span @click="sort">
          <img src="../assets/shizhong.svg" alt />
          <p>时间</p>
          <img src="../assets/paixusheng.svg" alt />
          <!-- <img src="../assets/paixusheng.svg" alt /> -->
        </span>
      </div>
      <div>
        <span @click="random">
          <img src="../assets/celebration_party-fu.svg" alt class="rotate" />
          <p>运气不错</p>
        </span>
      </div>
    </div>
    <div ref="mescroll" class="mescroll" id="mescroll">
      <ul class="note">
        <li
          v-for="(item,index) in noteList"
          :key="item.value"
          :class="[isHideList ?'hide-list':'']"
        >
          <div class="mask" v-show="currentIndex == index">
            <div @click.stop="deleteNote(item.id,index)">
              <img src="../assets/delete.svg" alt />
            </div>
          </div>
          <div
            class="list"
            @touchstart="touchS(index)"
            @touchmove="touchM"
            @touchend="touchE"
            @click="goNoteDetail(item.id)"
          >
            <div class="tag">
              <span
                v-for="items in item.tag"
                :key="items.vals"
                :style="{'backgroundColor':items.color}"
              >{{items.title}}</span>
            </div>
            <div class="content">
              <p>{{item.content}}</p>
              <p>{{item.created_at}}</p>
            </div>
          </div>
        </li>
        <div
          v-if="record"
          style="text-align:center;font-size: 1rem;padding-top:50px;"
        >你还没有记录，赶紧去记一个吧</div>
      </ul>
    </div>

    <AllTag v-show="allTag" @switchTag="switchTag" />
    <!-- 悬浮按钮 -->
    <div class="suspend-button">
      <router-link tag="div" to="/addrecord" class="edit-btn" v-if="allTag==false">
        <img src="../assets/edit.svg" alt />
      </router-link>
      <p v-if="allTag">
        <button :disabled="disabled" :class="{'dis-bg': !disabled}" @touchend="deleteTag(tagId)">
          删除
          <br />标签
        </button>
      </p>
    </div>
  </div>
</template>

<script>
var timeOutEvent = 0; //定时器
import MeScroll from "mescroll.js";
import "mescroll.js/mescroll.min.css";
import AllTag from "@/components/AllTag.vue";
import { log } from "util";
export default {
  name: "home",
  inject: ["reload"],
  components: {
    AllTag
  },
  data() {
    return {
      name: localStorage.getItem("name"),
      allTag: false,
      disabled: true,
      noteList: [],
      switchTagVal: "全部标签",
      currentIndex: -1,
      record: false,
      delState: false,
      temp: [],
      allTagVal: "",
      tagColor: "",
      tagId: "",
      isHideList: false,
      mescroll: null, // mescroll实例对象
      order_by: 1 // 排序：0=>倒序，1=>正序
    };
  },
  created() {
    if (localStorage.getItem("access_token") == null) {
      this.$router.replace("/register");
    }
  },
  methods: {
    sort(page) {
      if (this.order_by) {
        // 1 正序
        this.order_by = 0;
      } else {
        // 0 倒序
        this.order_by = 1;
      }
      // 上拉加载和下拉刷新  请求数据
      try {
        this.$api.note
          .notelist({
            access_token: localStorage.getItem("access_token"),
            order_by: this.order_by,
            page: page.num,
            pageSize: page.size
          })
          .then(res => {
            layer.open({
              type: 2,
              content: "加载中"
            });
            if (!res.error) {
              //如果是第一页需手动置空列表
              if (page.num == 1) this.noteList = [];
              this.noteList = this.noteList.concat(res.data.items);
            } else if (
              res.error == 40002 &&
              res.error == 40001 &&
              res.error == 40003
            ) {
              this.$router.replace("/register");
            } else {
              this.record = true;
              this.mescroll.endUpScroll(true);
            }
            //数据渲染成功后,隐藏下拉刷新的状态
            if (!res.error) {
              this.$nextTick(() => {
                this.mescroll.endSuccess(res.data.items.length);
              });
            }
            layer.closeAll("iframe");
          });
      } catch (e) {
        // 联网失败的回调,隐藏下拉刷新和上拉加载的状态;
        // this.mescroll.endErr();
      }
    },
    random() {
      try {
        this.$api.note
          .notelist({
            access_token: localStorage.getItem("access_token"),
            random: 1
          })
          .then(res => {
            if (res.error == 40001) {
              this.$router.push("/register");
            }
            if (!res.error) {
              this.goNoteDetail(res.data.items[0].id);
            }
            layer.open({
              content: res.msg,
              skin: "msg",
              time: 2
            });
          });
      } catch (e) {}
    },
    logout() {
      layer.open({
        content: "您是否要退出账号？",
        btn: ["确定", "不要"],
        yes: function(index) {
          localStorage.clear();
          location.reload();
          layer.close(index);
        }
      });
    },
    deleteNote(id, index) {
      // 删除note记事
      try {
        let data = {
          access_token: localStorage.getItem("access_token"),
          id: id
        };
        this.$api.note.notedelete({}, data).then(res => {
          layer.open({
            content: res.msg,
            skin: "msg",
            time: 2
          });
          if (!res.error) {
            setTimeout(() => {
              this.reload();
            }, 1000);
          }
        });
      } catch (e) {}
    },
    switchTag(obj, val) {
      // 子组件传过来的值 选择的标签
      if (obj == undefined) {
        this.switchTagVal = val;
        this.tagColor = "";
      } else {
        this.switchTagVal = obj.title;
        this.tagColor = obj.color;
        this.tagId = obj.id;
      }
    },
    upCallback(page) {
      this.sort(page);
    },
    sortByKey(array, key) {
      // 排序
      return array.sort(function(a, b) {
        var x = a[key];
        var y = b[key];
        return x < y ? 1 : x > y ? -1 : 0;
      });
    },
    allTagPopup() {
      this.allTag ? (this.allTag = false) : (this.allTag = true);
    },
    deleteTag(id) {
      try {
        let data = {
          access_token: localStorage.getItem("access_token"),
          id: id
        };
        this.$api.tag.tagdelete({}, data).then(res => {
          layer.open({
            content: res.msg,
            skin: "msg",
            time: 2
          });
          if (!res.error) {
            setTimeout(() => {
              this.reload();
            }, 1000);
          }
        });
      } catch (e) {}
    },
    homePageTouch() {
      this.currentIndex = -1;
      this.delState = false;
    },
    // 长按功能
    touchS(index) {
      let that = this;
      clearTimeout(timeOutEvent); //清除定时器
      timeOutEvent = 0;
      timeOutEvent = setTimeout(function() {
        that.currentIndex = index;
        that.delState = true;
      }, 600); //这里设置定时
    },
    touchE() {
      clearTimeout(timeOutEvent);
      if (timeOutEvent != 0) {
        timeOutEvent = 0;
      }
    },
    touchM() {
      clearTimeout(timeOutEvent); //清除定时器
      timeOutEvent = 0;
    },
    goNoteDetail(id) {
      // 去记事详情(修改记事)
      this.$router.push("/addrecord?id=" + id);
    },
    searchTag() {
      // 标签搜索
      this.allTag = false;
      try {
        let res = this.$api.note
          .notelist({
            access_token: localStorage.getItem("access_token"),
            tag_id: this.tagId.toString()
          })
          .then(res => {
            if (!res.error) {
              this.noteList = res.data.items;
            } else if (
              res.error == 40002 &&
              res.error == 40001 &&
              res.error == 40003
            ) {
              this.$router.replace("/register");
            } else {
              this.noteList = [];
            }
            layer.open({
              content: res.msg,
              skin: "msg",
              time: 2 //2秒后自动关闭
            });
          });
      } catch (e) {}
    }
  },
  watch: {
    switchTagVal: function(val) {
      if (val == "全部标签") {
        this.mescroll = new MeScroll("mescroll", {
          up: {
            callback: this.upCallback, //上拉加载的回调
            page: {
              num: 0,
              size: 10
            }
          }
        });
        this.allTag = false;
        this.disabled = true;
      } else {
        this.searchTag();
        this.disabled = false;
      }
    }
  },
  mounted: function() {
    this.mescroll = new MeScroll("mescroll", {
      up: {
        callback: this.upCallback, //上拉加载的回调
        page: {
          num: 0,
          size: 10
        }
      }
    });
  }
};
</script>

<style lang="less" scoped>
.text-algin {
  text-align: center;
}
.mescroll {
  position: fixed;
  top: 0rem;
  bottom: 0;
  height: auto; /*如设置bottom:50px,则需height:auto才能生效*/
}
.home {
  width: 100%;
  height: 100%;
  background-color: rgb(238, 238, 238);
  overflow-y: auto;
  header {
    width: 100%;
    position: fixed;
    z-index: 10;
    .state {
      height: 25px;
      background-color: rgb(10, 1, 35);
    }
    .nav {
      height: 60px;
      background-color: rgb(10, 1, 35);
      display: flex;
      > div {
        &:first-of-type {
          flex: 1;
          text-align: center;
          line-height: 60px;
        }
        &:nth-of-type(2) {
          flex: 2;
          button {
            border: none;
            outline: none;
            width: 6rem;
            height: 2.2rem;
            color: #000;
            text-align: center;
            font-size: 1rem;
            border-radius: 0.2rem;
            position: relative;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
          }
        }
        &:last-of-type {
          flex: 1;
          img {
            width: 1.2rem;
            position: relative;
            right: -3rem;
            top: 50%;
            transform: translateY(-50%);
          }
        }
      }
    }
  }
  .choose-btn {
    width: 100%;
    height: 7.4rem;
    padding-top: 60px;
    display: flex;
    div {
      flex: 1;
      padding: 0.6rem 1rem;
      span {
        display: block;
        width: 100%;
        height: 100%;
        margin: 0 auto;
        color: #fff;
        background-color: rgb(10, 1, 35);
        border-radius: 0.4rem;
        display: flex;
        // padding-left: 2.6rem;

        img {
          width: 1rem;
          // max-width: 1rem;
          // min-width: 1rem;
        }
        p {
          line-height: 2.5rem;
          padding: 0 0.8rem 0 0.2rem;
        }
        img:last-of-type {
          width: 1.3rem;
        }
        .rotate {
          width: 1.1rem !important;
          transform: rotateZ(45deg);
        }
      }
      span:first-of-type {
        padding-left: 2.2rem;
      }
    }
  }
  .mescroll[data-v-fae5bece] {
    position: relative;
    top: 0rem;
    bottom: 0;
    height: auto;
  }
  .note {
    width: 94%;
    margin: 0 auto;
    margin-bottom: 1.4rem;
    .hide-list {
      height: 0;
      opacity: 0;
    }
    li {
      margin: 1.4rem 0;
      // height: 8.4rem;
      overflow: hidden;
      position: relative;
      transition: all 0.5s;
      .mask {
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.6);
        position: absolute;
        z-index: 99;
        div,
        div img {
          position: relative;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
        div {
          width: 4rem;
          height: 4rem;
          border-radius: 50%;
          background-color: #fff;
          z-index: 13;
          position: absolute;

          img {
            width: 2.5rem;
            z-index: 13;
          }
        }
      }
      .list {
        background-color: #fff;
        border-radius: 0.2rem;
        box-shadow: 0rem 0.1rem 0.3rem #ccc;
      }
      .tag {
        padding: 0.3rem 0 0 0.3rem;
        min-height: 2.6rem;
        background-color: rgb(223, 223, 223);
        span {
          min-height: 2.4rem;
          max-height: 2.4rem;
          line-height: 2.4rem;
          padding: 0 0.7rem;
          margin-right: 0.3rem;
          margin-bottom: 0.3rem;
          font-size: 1rem;
          letter-spacing: 0.05rem;
          color: #fff;
          display: inline-block;
          border-radius: 0.3rem;
        }
      }
      .content {
        padding: 0.5rem;
        margin-top: 0.5rem;
        font-size: 1rem;
        line-height: 1.1rem;
        letter-spacing: 0.1rem;
        p:first-of-type {
          font-size: 1.2rem;
        }
        p:last-of-type {
          color: #aaa;
          margin-top: 0.8rem;
        }
      }
    }
  }

  .suspend-button {
    width: 4rem;
    height: 4rem;
    background-color: rgb(10, 1, 35);
    position: fixed;
    right: 0.5rem;
    bottom: 0.5rem;
    border-radius: 50%;
    p,
    img {
      position: relative;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    .edit-btn {
      width: 100%;
      height: 100%;
      img {
        width: 40%;
      }
    }
    p {
      width: 100%;
      height: 100%;
      color: #fff;
      text-align: center;
      button {
        width: 100%;
        height: 100%;
        outline: none;
        text-align: center;
        border-radius: 50%;
        border: none;
        color: #fff;
        background-color: rgb(114, 114, 114);
      }
      .dis-bg {
        background-color: #f75953;
      }
    }
  }
}
.abspp {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #999;
  z-index: 12;
}
</style>
